//
//  USPhotoPreviewCell.m
//  us
//
//  Created by karry on 2025/5/16.
//

#import "USPhotoPreviewCell.h"
#import <AVKit/AVKit.h>
#import <Photos/Photos.h>
#import <AVFoundation/AVFoundation.h>

#import "USPhotoCell.h"
#import "USMediaLivePhotoManager.h"
@interface USPhotoPreviewCell ()

@property (nonatomic, strong) USPhotoModel *photoModel;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIButton *playButton;

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;

@property (nonatomic, strong) UIView *liveTagView;
@property (nonatomic, strong) PHLivePhotoView *livePhotoView;
@property (nonatomic, strong) NSURL *liveImageUrl;
@property (nonatomic, strong) NSURL *liveVideoUrl;

@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, strong) UIButton *downloadButton;


@end

@implementation USPhotoPreviewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupViews];
    }
    return self;
}

- (void)prepareForReuse {
    [super prepareForReuse];
    [self stopVideoIfNeeded];
    self.imageView.image = nil;
    self.playButton.hidden = YES;
}

- (void)setupViews {
    self.contentView.backgroundColor = [UIColor blackColor];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)];
    [self.contentView addGestureRecognizer:tap];

    
    self.imageView = [[UIImageView alloc] initWithFrame:self.contentView.bounds];
    self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.imageView.clipsToBounds = YES;
    [self.contentView addSubview:self.imageView];
    
 
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithPointSize:60 weight:UIImageSymbolWeightRegular];
    UIImage *image = [UIImage systemImageNamed:@"play.circle.fill" withConfiguration:config];
    [self.playButton setImage:image forState:UIControlStateNormal];
    self.playButton.tintColor = [UIColor whiteColor];
    [self.playButton addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.playButton];
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
    }];
    
    //live
    self.livePhotoView = [[PHLivePhotoView alloc] init];
    self.livePhotoView.contentMode = UIViewContentModeScaleAspectFit;
    [self.contentView addSubview:self.livePhotoView];
    self.livePhotoView.hidden = YES;
    [self.livePhotoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.contentView);
    }];

    [self.livePhotoView addSubview:self.liveTagView];
    [self.liveTagView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(12);
        make.centerX.mas_equalTo(0);
        make.height.mas_equalTo(30);
    }];
    
    // 删除按钮
    self.deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.deleteButton setImage:[UIImage imageNamed:@"preview_delete"] forState:UIControlStateNormal];
    [self.deleteButton addTarget:self action:@selector(deleteTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.deleteButton];
    self.deleteButton.hidden = YES;
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.bottom.mas_equalTo(self.contentView.mas_safeAreaLayoutGuideBottom).offset(-30);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(28);
    }];
    
    // 下载按钮
    self.downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.downloadButton setImage:[UIImage imageNamed:@"preview_download"] forState:UIControlStateNormal];
    [self.downloadButton addTarget:self action:@selector(downloadTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.downloadButton];
    [self.downloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.bottom.mas_equalTo(self.contentView.mas_safeAreaLayoutGuideBottom).offset(-30);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(28);
    }];
    
    // 下载按钮
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:[[UIImage imageNamed:@"ic_close"] imageWithTintColor:UIColor.whiteColor] forState:UIControlStateNormal];
    
    [closeBtn addTarget:self action:@selector(closeTapped) forControlEvents:UIControlEventTouchUpInside];
    closeBtn.tintColor = UIColor.whiteColor;
    [self.contentView addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.equalTo(self.liveTagView);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(40);
    }];
}
- (UIView *)liveTagView {
    if (_liveTagView == nil) {
        _liveTagView = [[UIView alloc] init];
        _liveTagView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        _liveTagView.layer.cornerRadius = 4;
        _liveTagView.layer.masksToBounds = YES;

        UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"livephoto"]];
        iconView.contentMode = UIViewContentModeScaleAspectFit;
        [_liveTagView addSubview:iconView];
        
        UILabel *label = [[UILabel alloc] init];
        label.text = @"LIVE";
        label.textColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:15];
        [_liveTagView addSubview:label];

        [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(6);
            make.centerY.equalTo(_liveTagView);
            make.width.height.mas_equalTo(20);
        }];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(iconView.mas_right).offset(4);
            make.right.mas_equalTo(-6);
            make.centerY.equalTo(_liveTagView);
        }];
    }
    return _liveTagView;
}

- (void)setShowBotTool:(BOOL)showBotTool {
    _showBotTool = showBotTool;
    self.deleteButton.hidden = !showBotTool;
}
- (void)configureWithModel:(USPhotoModel *)model {
    _photoModel = model;
    [self stopVideoIfNeeded];
    
 
    if (model.type == USMediaTypeImage) {
        // 图片
        self.playButton.hidden = YES;
        self.livePhotoView.hidden = YES;
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.cosUrl] placeholderImage:nil];
    } else if (model.type == USMediaTypeVideo) {
        // 视频
        self.playButton.hidden = NO;
        self.livePhotoView.hidden = YES;
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.cosUrl.videoThumbnail]];
        
    }else if (model.type == USMediaTypeLivePhoto) {
        //live
        self.playButton.hidden = YES;
        self.livePhotoView.hidden = NO;
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:model.cosUrl]];

        [self loadLivePhoto];
    }
}

- (void)playVideo {
    // 避免重复创建
    if (!self.player) {
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.photoModel.cosUrl]];
        self.player = [AVPlayer playerWithPlayerItem:item];
        self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        self.playerLayer.frame = self.contentView.bounds;
        self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
        [self.contentView.layer addSublayer:self.playerLayer];
        
        // 播放结束后显示播放按钮
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(videoDidFinishPlaying)
                                                     name:AVPlayerItemDidPlayToEndTimeNotification
                                                   object:item];
    }
    
    // 播放
    [self handleTap];
}

- (void)pauseIfPlaying {
    if (self.photoModel.type == USMediaTypeVideo && self.player && self.player.rate > 0) {
        [self.player pause];
        self.playButton.hidden = NO;
        [self.contentView bringSubviewToFront:self.playButton];
    }
}


- (void)handleTap {
    if (self.photoModel.type == USMediaTypeVideo && self.player) {
        if (self.player.rate == 0.0) {
            [self.player play];
            self.playButton.hidden = YES;
        } else {
            [self.player pause];
            self.playButton.hidden = NO;
            [self.contentView bringSubviewToFront:self.playButton];
        }
    }
}

- (void)videoDidFinishPlaying {
    [self.player seekToTime:kCMTimeZero];
    [self.playerLayer removeFromSuperlayer];
    self.player = nil;
    self.playerLayer = nil;
    self.playButton.hidden = NO;
}

- (void)stopVideoIfNeeded {
    if (self.player) {
        [self.player pause];
        [self.playerLayer removeFromSuperlayer];
        self.player = nil;
        self.playerLayer = nil;
    }
    self.playButton.hidden = YES;
}
 
#pragma mark - 创建 Live Photo

- (void)loadLivePhoto {
    // 假设你有两个网络地址，分别是图片和视频资源
    NSURL *imageURL = [NSURL URLWithString:self.photoModel.cosUrl];
    NSURL *videoURL = [NSURL URLWithString:self.photoModel.liveMovUrl];

    NSLog(@"imageURL = %@",imageURL.absoluteString);
    NSLog(@"videoURL = %@",videoURL.absoluteString);
    
    // 下载图片
    [self downloadResourceFromURL:imageURL completion:^(NSURL *imageLocalURL, NSError *error) {
        if (error) {
            NSLog(@"Failed to download image: %@", error);
            return;
        }
  
        // 下载视频
        [self downloadResourceFromURL:videoURL completion:^(NSURL *videoURL, NSError *error) {
            if (error) {
                NSLog(@"Failed to download video: %@", error.localizedDescription);
                return;
            }
            
            // 下载完成后，创建 Live Photo
            [self createLivePhotoWithImage:imageLocalURL videoURL:videoURL];
        }];
    }];
}
- (void)createLivePhotoWithImage:(NSURL *)imageURL videoURL:(NSURL *)videoURL {

    @weakify(self)
    [USMediaLivePhotoManager assembleLivePhotoWithImageURL:imageURL videoURL:videoURL identifier:[NSUUID UUID].UUIDString completion:^(PHLivePhoto * _Nonnull livePhoto, NSURL * _Nonnull pairedImageURL, NSURL * _Nonnull pairedVideoURL, NSError * _Nonnull error) {
     
        @strongify(self)
        if (livePhoto) {
                        
            self.liveImageUrl = pairedImageURL;
            self.liveVideoUrl = pairedVideoURL;
         
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"合成live成功");
                self.livePhotoView.livePhoto = livePhoto;
                [self.livePhotoView startPlaybackWithStyle:PHLivePhotoViewPlaybackStyleFull];
            });
        } else {
            NSLog(@"Failed to create Live Photo.");
        }
        
    }];
 
}
- (void)downloadResourceFromURL:(NSURL *)url completion:(void (^)(NSURL *localURL, NSError *error))completion {
    NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:url
                                                                     completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(nil, error);
            });
            return;
        }
        NSString *fileName = url.lastPathComponent;
        NSString *destinationPath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
        NSURL *destinationURL = [NSURL fileURLWithPath:destinationPath];
        
        [[NSFileManager defaultManager] removeItemAtURL:destinationURL error:nil]; // 清除旧文件
        [[NSFileManager defaultManager] moveItemAtURL:location toURL:destinationURL error:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(destinationURL, nil);
        });
    }];
    [task resume];
}

- (void)closeTapped {
    if (self.onCloseTapped) {
        self.onCloseTapped();
    }
}

- (void)deleteTapped {
    if (self.onDeleteTapped) {
        self.onDeleteTapped();
    }
}

- (void)downloadTapped {
    NSURL *url = [NSURL URLWithString:self.photoModel.cosUrl];
    
    if (self.photoModel.type == USMediaTypeImage) {
        // 图片下载
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url
                                                            completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            if (image && finished) {
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    [PHAssetChangeRequest creationRequestForAssetFromImage:image];
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    if (success) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self makeToast:@"下载成功"];
                        });                    }
                    NSLog(@"图片保存 %@", success ? @"成功" : @"失败");
                }];
            }
        }];
    } else if (self.photoModel.type == USMediaTypeVideo) {
        // 视频下载
        NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (location && !error) {
                NSData *videoData = [NSData dataWithContentsOfURL:location];
                NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[url lastPathComponent]];
                [videoData writeToFile:tempPath atomically:YES];
                
                [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                    [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL fileURLWithPath:tempPath]];
                } completionHandler:^(BOOL success, NSError * _Nullable error) {
                    if (success) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self makeToast:@"下载成功"];
                        });
                    }
                    NSLog(@"视频保存 %@", success ? @"成功" : @"失败");
                }];
            }
        }];
        [task resume];
    } else if (self.photoModel.type == USMediaTypeLivePhoto) {
        
        [self saveLivePhotoToAlbumWithImageURL:self.liveImageUrl videoURL:self.liveVideoUrl completion:^(BOOL success, NSError *error) {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self makeToast:@"下载成功"];
                });
            }
        }];
    }
}


- (void)saveLivePhotoToAlbumWithImageURL:(NSURL *)imageURL
                              videoURL:(NSURL *)videoURL
                           completion:(void(^)(BOOL success, NSError *error))completion
{
 
    // 保存到相册
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetCreationRequest *request = [PHAssetCreationRequest creationRequestForAsset];
        
        // 添加图片资源
        [request addResourceWithType:PHAssetResourceTypePhoto
                            fileURL:imageURL
                           options:nil];
        
        // 添加视频资源（关键：必须使用PHAssetResourceTypePairedVideo）
        [request addResourceWithType:PHAssetResourceTypePairedVideo
                            fileURL:videoURL
                           options:nil];
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
 
        if (completion) completion(success, error);
    }];
}

@end

